import { defineStore } from 'pinia';
import { IUser } from '@/store/types';
import { store } from '@/store';
import { reqUpdatePassword, reqUpdateUserinfo, reqUserinfo } from '@/api/module/userApi';
import { IUpdatePasswordParam, IUpdateUserinfoParam } from '@/api/types';
import { useAuthStore } from '@/store/module/useAuthStore';
import { ElMessage } from 'element-plus';

const USER = 'userinfo';
const userinfoSetting: IUser = {
  accountNonExpired: false,
  accountNonLocked: false,
  address: '',
  authorities: undefined,
  clinicId: 0,
  credentialsNonExpired: false,
  email: '',
  enabled: false,
  headImg: '',
  id: 0,
  idCard: '',
  isAdmin: false,
  isEnable: false,
  lastloginTime: undefined,
  occupation: '',
  password: '',
  personName: '',
  registerTime: '',
  sex: '',
  tel: '',
  username: '',
};

export const useUserinfoStore = defineStore(USER, {
  state: (): IUser => userinfoSetting,
  getters: {},
  actions: {
    initStore() {
      const authStore = useAuthStore();
      if (authStore.isLogged()) {
        this.getUserinfo();
      }
    },
    getUserinfo() {
      reqUserinfo().then((res) => {
        this.load(res.data);
      });
    },
    load(data: IUser) {
      this.$patch({
        ...data,
      });
    },
    unload() {
      this.$patch({
        ...{
          accountNonExpired: false,
          accountNonLocked: false,
          address: '',
          authorities: undefined,
          clinicId: 0,
          credentialsNonExpired: false,
          email: '',
          enabled: false,
          headImg: '',
          id: 0,
          idCard: '',
          isAdmin: false,
          isEnable: false,
          lastloginTime: undefined,
          occupation: '',
          password: '',
          personName: '',
          registerTime: '',
          sex: '',
          tel: '',
          username: '',
        },
      });
    },
    updateUserinfo(param: IUpdateUserinfoParam, callback?: Function) {
      reqUpdateUserinfo(param)
        .then((res) => {
          this.getUserinfo();
          ElMessage.success({ message: '修改信息成功！' });
          callback && callback(true);
        })
        .catch(() => {
          callback && callback(false);
        });
    },
    updatePassword(param: IUpdatePasswordParam, callback?: Function) {
      reqUpdatePassword(param)
        .then((res) => {
          callback && callback(true);
        })
        .catch(() => {
          callback && callback(false);
        });
    },
  },
});
/**
 * 在setup外使用store
 */
export const useUserStoreWithOut = () => {
  return useUserinfoStore(store);
};

// //添加订阅
// const userStore = useUserStoreWithOut();
// userStore.$subscribe((mutation, state) => {
//   local.set(mutation.storeId, JSON.stringify(state));
// });
